<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/22
 * Time: 11:11
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\common\business\BusUser;
use app\common\lib\Str;
use app\common\model\BuddhaArticle;
use app\common\model\BuddhaArticleClick;
use app\common\model\BuddhaOrder;
use app\api\model\WeixinUser;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallOrder;
use app\common\model\PointReceive;
use app\common\model\WeixinExpress;
use app\common\model\WeixinExpressConfig;
use app\common\model\WeixinIntegral;
use app\common\model\WeixinUserCard;

class User extends Base
{
    /**
     * 更新用户信息
     * @return array|\think\response\Json
     */
    public function updateByUserInfo()
    {
        $nickName = $this->request->param('nickName', '', 'trim');
        $avatarUrl = $this->request->param('avatarUrl', '', 'trim');
        $openid = $this->request->openid;
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "用户错误");
        }
//        dump($nickName);exit();
//        $res = (new WeixinUser())->where('openid',$openid)->update([
//            "nickName" => strval($nickName),
////                "nick"=>$nickName,
//            "avatarUrl" => $avatarUrl,
//            "openid" => $openid
//        ]);
//        dump((new WeixinUser())->getLastSql());exit();
        //dump(rawurldecode($nickName));exit();
        $bStr = Str::has_special_char($nickName);
        if ($bStr) {
            $nickName = rawurlencode($nickName);
        }
        try {
            $result = (new WeixinUser())->updateByUserInfo([
                "nickName" => $nickName,
//                "nick"=>$nickName,
                "avatarUrl" => $avatarUrl,
                "openid" => $openid
            ]);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", $result);
    }

    /**
     * 获取捐赠金额
     * @return array|\think\response\Json
     */
    public function getUserByList()
    {
        $openid = $this->request->param('openid', '', 'trim');
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "用户错误");
        }
        try {
            $money = (new BuddhaOrder())
                ->field('sum(money) as money')
                ->where('openid', $openid)
                ->where('payment', 1)
                ->find();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            "money" => $money['money'] ?? 0.00
        ]);
    }

    //获取我的查看
    public function getArticleByList()
    {
        $openid = $this->request->param('openid', '', 'trim');
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "用户错误");
        }
        try {
            $lists = (new BuddhaArticleClick())
                ->field('a.article_id,a.create_time,p.title,p.short_title,p.logo,p.tag,p.id as id')
                ->alias('a')
                ->join('buddha_article p', 'a.article_id = p.id')
                ->where('openid', $openid)
                ->paginate(10)->toArray();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "发生错误");
        }
        $row = [];
        if (!empty($lists['data'])) {
            foreach ($lists['data'] as $k => $v) {
                $row[$k] = $v;
                $tag = (new BuddhaArticle())->getBaseById($v['tag']);
                $row[$k]['tag'] = $tag ?? [];
            }
            $lists['data'] = $row;
        }
        return Show::json_show(Status::mini_normal, "ok", $lists);
    }

    /**
     * 获取个人中心数据
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfoList()
    {
        //获取积分
        $integral = (new PointReceive())->getUserIntegralSurplus($this->m_openid);
        //获取取件次数
        $express = (new WeixinExpress())->getUserExpressSurplus($this->m_openid);
        //获取 订单数量
        try {
            $order = (new MallOrder())->getUserOrderByCount($this->m_openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询失败");
        }
        $order_count = [];
        if (!empty($order)) {
            foreach ($order as $v) {
                switch ($v['status']) {
                    case 0:
                    case 5:
                        if (isset($order_count['loading'])) {
                            $order_count['loading'] += $v['count'];
                        } else {
                            $order_count['loading'] = $v['count'];
                        }
                        break;
                    case 1:
                        if (isset($order_count['normal'])) {
                            $order_count['normal'] += $v['count'];
                        } else {
                            $order_count['normal'] = $v['count'];
                        }
                        break;
                    case 2:
                        if (isset($order_count['loading_normal'])) {
                            $order_count['loading_normal'] += $v['count'];
                        } else {
                            $order_count['loading_normal'] = $v['count'];
                        }
                        break;
                    case 3:
                        if (isset($order_count['success'])) {
                            $order_count['success'] += $v['count'];
                        } else {
                            $order_count['success'] = $v['count'];
                        }
                        break;
                    case 4:
                        if (isset($order_count['ref'])) {
                            $order_count['ref'] += $v['count'];
                        } else {
                            $order_count['ref'] = $v['count'];
                        }
                        break;
                    case 6:
                        if (isset($order_count['loading_q'])) {
                            $order_count['loading_q'] += $v['count'];
                        } else {
                            $order_count['loading_q'] = $v['count'];
                        }
                        break;
                    case 7:
                        if (isset($order_count['beihuo'])) {
                            $order_count['beihuo'] += $v['count'];
                        } else {
                            $order_count['beihuo'] = $v['count'];
                        }
                        break;
                    case 8:
                        if (isset($order_count['jiedan'])) {
                            $order_count['jiedan'] += $v['count'];
                        } else {
                            $order_count['jiedan'] = $v['count'];
                        }
                        break;
                    case 9:
                        if (isset($order_count['cancel'])) {
                            $order_count['cancel'] += $v['count'];
                        } else {
                            $order_count['cancel'] = $v['count'];
                        }
                        break;
                }
            }
        }
        //获取剩余积分
        $result = [
            "integral" => $integral ?? 0,  //剩余积分
            "express" => $express ?? 0,  //剩余取件次数
            "balance" => $balance ?? 0, //剩余余额
            "type" => "v1",   //会员等级
            "count" => $order_count
        ];
        return Show::json_show(Status::mini_normal, "ok", $result);
    }

    /**
     * 查询是否申请会员卡
     * @return array|\think\response\Json|void
     * @throws \think\Exception
     */
    public function getUserInfoBalance()
    {
        //查询是都有会员信息
        $row = (new WeixinUserCard())->getBaseByWhereOne(['openid' => $this->m_openid]);
        if (empty($row)) {
            return Show::json_show(Status::mini_normal, "ok", [
                "status" => -1
            ]);
        } else {
            if ($row['status'] == 0) {
                return Show::json_show(Status::mini_normal, "ok", [
                    "status" => 0,
                    "list" => $row
                ]);
            } else if ($row['status'] == 1) {
                return Show::json_show(Status::mini_normal, "ok", [
                    "status" => 1,
                    "list" => $row
                ]);
            } else if ($row['status'] == 2) {
                return Show::json_show(Status::mini_normal, "ok", [
                    "status" => 2,
                    "list" => $row
                ]);
            }
        }
    }

    /**
     * 添加会员卡
     * @return array|\think\response\Json
     * @throws \think\Exception
     */
    public function addUserCard()
    {
        $realName = $this->request->param('name', '', 'trim');
        $birthday = $this->request->param('birthday', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');
        $sex = $this->request->param('sex', '', 'trim');
        if (empty($realName)) {
            return Show::json_show(Status::mini_error, "请输入姓名");
        }
        $birthday = strtotime($birthday);
        if ($birthday === false) {
            return Show::json_show(Status::mini_error, "出生年月错误");
        }
        if (empty($sex) || !in_array($sex, ['男', '女', '保密'])) {
            return Show::json_show(Status::mini_error, "选择性别");
        }
        if (empty($mobile) || !preg_match('/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/', $mobile)) {
            return Show::json_show(Status::mini_error, "手机号不正确");
        }
        $data = [
            "realName" => $realName,
            "birthday" => $birthday,
            "mobile" => $mobile,
            "openid" => $this->m_openid,
            "status" => 1
        ];
        if ($sex == '男') {
            $data['sex'] = 2;
        } else if ($sex == "女") {
            $data['sex'] = 1;
        } else {
            $data['sex'] = 0;
        }
        $obj = new WeixinUserCard();
        $obj->startTrans();
        try {
            $row = $obj->getBaseByListFind(['openid' => $this->m_openid]);

            if ($row) {
                $data['update_time'] = time();
                $data['status'] = 0;
                $res = $row->save($data);

            } else {
                //赠送积分
                $config = (new WeixinExpressConfig())->getBaseById(1);
                (new WeixinExpress())->insertSaveById([
                    "num" => $config['number'],
                    "openid" => $this->m_openid,
                    "source" => 1
                ]);
                $res = $obj->save($data);
            }
            $obj->commit();
        } catch (\Exception $e) {
            $obj->rollback();
            return Show::json_show(Status::mini_error, "操作失败");
        }
        if ($res) {
            return Show::json_show(Status::mini_normal, "操作成功");
        } else {
            return Show::json_show(Status::mini_error, "操作失败");
        }
    }

    /**
     * 更新用户选择的店铺
     * @return array|\think\response\Json
     */
    public function getUpdateUser()
    {
        $shop_id = $this->request->param('id', 0, 'intval');
        $update_data = [
            "shop_id" => $shop_id,
            "openid" => $this->m_openid
        ];
        try {
            $user = (new WeixinUser())->updateByUserInfo($update_data);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", $user);
    }

    public function getPhoneNumber()
    {
        $code = $this->request->param('code', '', 'trim');
        $iv = $this->request->param('iv', '', 'trim');
        $encryptedData = $this->request->param('encryptedData', '', 'trim');
        $session_key = $this->mini_app->auth->session($code);

        if (empty($session_key['session_key'])) {
            return Show::json_show(Status::mini_error, "内部异常");
        }
        $result = $this->mini_app->encryptor->decryptData($session_key['session_key'], $iv, $encryptedData);
        if (empty($result['phoneNumber'])) {
            return Show::json_show(Status::mini_error, "更新失败");
        }
        $update_data = [
            "mobile" => $result['phoneNumber'],
            "update_time" => time(),
            "openid" => $this->m_openid
        ];
        try {
            $user = (new WeixinUser())->updateByUserInfo($update_data);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", $user);
    }
}